package com.mxpio.erp.equipment.job;

import cn.hutool.core.date.DateUtil;
import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentRepair;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

//维修单评价45天后归档
@Slf4j
@Component
public class EquipmentRepairZippedJob implements Job {

    private String parameter;

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }
    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("维修任务自动归档job执行开始："+DateUtil.formatDateTime(new Date()));
        Object params = context.getJobDetail().getJobDataMap().get("params");
        Integer zipOffSetDay = 45;//默认45天，可以在任务中配置
        if (params!=null&& StringUtils.isNumeric(params.toString())){
            zipOffSetDay = Integer.parseInt(params.toString());
        }
        String daysBefore = DateUtil.formatDate(DateUtils.addDays(new Date(),0-zipOffSetDay));
        Criteria dateCriteria = Criteria.create();
        dateCriteria.addCriterion("evaluateDate", Operator.LT,daysBefore);//根据评价时间来判断时间，（归当前允许修改，所以不能根据updateTime来判断）
        List<EquipmentRepair> repairList = JpaUtil.linq(EquipmentRepair.class).equal("repairStatus", EquipmentEnums.RepairStatus.ZIPING.getCode()).where(dateCriteria).list();
        if (repairList.size()>0){
            for (EquipmentRepair repair:repairList){
                repair.setRepairStatus(EquipmentEnums.RepairStatus.ZIPPED.getCode());
                JpaUtil.update(repair);
            }
        }
        log.info("维修任务自动归档job执行结束："+DateUtil.formatDateTime(new Date()));
    }
}
